<template>
    <div>
        <el-dialog v-model="isShow" :title="isAdd ? '添加角色' : '编辑角色'" center @close="cancel(formRef)">
            <el-form :model="form" :rules="rules" ref="formRef">
                <el-form-item prop='rolename' label="角色名称" :label-width="formLabelWidth">
                    <el-input v-model="form.rolename" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色权限" :label-width="formLabelWidth">
                    <el-tree default-expand-all :data="menulist" show-checkbox node-key="id" ref="treeRef" :props="{
                        children: 'children',
                        label: 'title',
                    }" highlight-current>
                    </el-tree>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(formRef)">取消</el-button>
                    <el-button type="primary" @click="comfirm(formRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { roleAdd, roleEdit, roleInfo } from '@/request/api';
import { ref, reactive, defineProps, defineEmits, defineExpose, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElTree, ElMessage } from 'element-plus'
import { useStore } from 'vuex';
const store = useStore()
const menulist = computed(() => store.getters['menu/getMenuList'])
let newId = 0
const getMenu = () => {
    store.dispatch('menu/MenuListActions')
}
getMenu()
const getRole = () => {
    store.dispatch('role/RoleListActions')
}


const formLabelWidth = '140px'

let formRef = ref<FormInstance>()

const treeRef = ref<InstanceType<typeof ElTree>>()

const form = ref<any>({
    rolename: '',// 角色名称
    menus: '',    //角色权限 id数组
    status: 1   //状态1正常2禁用 
})

const rules = reactive<FormRules>({
    rolename: [
        { required: true, message: "请输入角色名称", trigger: "blur" },
        { min: 3, max: 7, message: "长度在 3 到 7 个字符", trigger: "blur" },
    ]
})

let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})


// 重置
let reset = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields(),
        form.value = {
            rolename: '',// 角色名称
            menus: '',    //角色权限 id数组
            status: 1   //状态1正常2禁用 
        }
    treeRef.value!.setCheckedKeys([], false)
}

let emit = defineEmits(['cancel'])
// 取消
const cancel = (formEl: FormInstance | undefined) => {
    emit('cancel')
    reset(formEl)
}


// 获取一条数据
let lookup = (id: any) => {
    newId = id
    // console.log(id,'idididi');
    roleInfo({
        id
    }).then(res => {
        console.log(res, '获取一条角色列表数据');
        form.value = res.list
        form.value.id = id
        treeRef.value!.setCheckedKeys(
            form.value.menus ? form.value.menus.split(',') : []
        )
    })
}

defineExpose({
    lookup
})

// 确定
const comfirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            form.value.menus = treeRef.value!.getCheckedKeys() ? treeRef.value!.getCheckedKeys().join(',') : '';
            console.log(form.value, '表单对象');
            if (props.isAdd) {
                roleAdd(form.value)
                    .then(res => {
                        console.log(res, '角色添加');
                        if (res.code == 200) {
                            ElMessage({
                                type: 'success',
                                message: res.msg
                            })
                            cancel(formEl)
                            getRole()
                        }
                    })
            } else {
                roleEdit({
                    ...form.value,
                    id: newId
                })
                    .then(res => {
                        console.log(res, '角色编辑');
                        if (res.code == 200) {
                            ElMessage({
                                type: 'success',
                                message: res.msg
                            })
                            cancel(formEl)
                            getRole()
                        }
                    })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}



</script>

<style scope>
</style>
